package LeetCode.LinkedList;

/**
 * @author : LdLtd
 * @Date : 2023/8/6
 * @Description:24. 两两交换链表中的节点
 */
public class swap_nodes_in_pairs {

    class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }


    /*递归做法
    * 输入：head = [1,2,3,4]
    输出：[2,1,4,3]*/
    class Solution {
        public ListNode swapPairs(ListNode head) {
            if (head == null || head.next == null) {
                return head;
            }

            ListNode node = head.next;
            ListNode next = swapPairs(node.next);
            node.next = head;
            head.next = next;

            return node;

        }
        public ListNode swapPairs1(ListNode head) {
            ListNode p = new ListNode(0);
            p.next=head;
            ListNode t=p;
            while (t.next!=null&&t.next.next!=null){
                ListNode start = t.next;
                ListNode end = t.next.next;
                t.next= end;
                start.next=end.next;
                end.next=start;
                t=start;
            }
            return p.next;
        }
    }

}
